package Power_Asisst.main;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import Power_Asisst.main.TCP_Services.ServerThread;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
public class Power_AsisstActivity extends Activity {
	
	UDP_Services SVBroadCast= new UDP_Services();
	Untils SVUntils = new Untils();
	private TextView serverStatus;
	private ListView listViewItem;
	static final int PROGRESS_DIALOG=0;
	int currentNumber;
	final Handler handler = new Handler();
	public static String SERVERIP="";
	private ServerSocket serverSocket;
	public static int SERVERPORT=8080;
	public  String result="None";
	public int StatusConnect=0;
	private ListView lvItem;
	//AlertDialog.Builder builder;
	//AlertDialog alertDialog;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       final TextView myTextView =(TextView)findViewById(R.id.textViewReceive);
       final Button btnSend =(Button) findViewById(R.id.btnSend);
       final Button btnExit = (Button) findViewById(R.id.btnExit);
       final Button btnConnect=(Button)findViewById(R.id.btnConnect);
       serverStatus=(TextView)findViewById(R.id.textViewReceive);
       SERVERIP=SVUntils.getLocalIPAddress();
       		if(StatusConnect!=1)
       		{
       			Thread testListenTCP = new Thread(new ServerThread());
    			testListenTCP.start();
       		}
       		else{
       			updateStatus();
       		}
			
			
		
        btnSend.setOnClickListener(new View.OnClickListener() {
       
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				try {
				//	show("");
					Thread testBroadCast = new Thread(new BroadCastThread());
					testBroadCast.start();
					
				} catch (Exception e) {
					// TODO: handle exception
					Log.d("Co loi trong chay Thread", e.toString());
				}
				
			}
		});
    btnExit.setOnClickListener(new View.OnClickListener() {
			
    	  
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				try {
				finish();
				android.os.Process.killProcess(android.os.Process.myPid());
				
					
				} catch (Exception e) {
					// TODO: handle exception
					Log.d("Loi khi exit", e.toString());
				}
			}
		});
       btnConnect.setOnClickListener(new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			updateStatus();
		}
	});
    }
    public void updateStatus()
    {
    	if(StatusConnect==1)
    	{
    		testShow(result);
    	}
    }
    public void updateUI(String mess)
    {
    	serverStatus.setText(mess);
    }
    public void testShow(String input)
	{
		String[] result=input.split(",");
		new AlertDialog.Builder( this )
		.setTitle( "Thông Báo" )
		.setMessage( "Bạn sẽ kết nối đến: "+result[0]+" ("+result[1]+")" )
		.setPositiveButton( "Đồng ý", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Log.d( "AlertDialog", "Positive" );
				try {
					
					// goi intent
					//Intent intent = new Intent();
			    	//intent.setClass(getBaseContext(),RemotePowerPoint.class);
					//startActivity(intent);
				} catch (Exception e) {
					// TODO: handle exception
					Log.e("Loi intent moi", e.toString());
				}
				
			}
		})
		.setNegativeButton( "Hủy", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Log.d( "AlertDialog", "Negative" );
			}
		} )
		.show();
	}
    public class ServerThread implements Runnable {
    	final Handler myHandler= new Handler();
	    public  void run() {
	    	
	        try {
	            if (SERVERIP != null) {
	            	(new Thread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							final String status= SERVERIP;
							myHandler.post(new Runnable() {
								
								@Override
								public void run() {
									// TODO Auto-generated method stub
									updateUI(status);
								}
							});
						}
					})).start();
	                serverSocket = new ServerSocket(SERVERPORT);
	                while (true) {
	              
	                	//serverStatus.setText(SERVERIP);
	                    // listen for incoming clients
	                    Socket client = serverSocket.accept();
	                    (new Thread(new Runnable() {
							
							@Override
							public void run() {
								// TODO Auto-generated method stub
								myHandler.post(new Runnable() {
									
									@Override
									public void run() {
										// TODO Auto-generated method stub
										updateUI("");
									}
								});
							}
						})).start();
	                   try {
	                        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
	                        final String line=in.readLine();
	                        while (line != null)
	                        {
	                        	handler.post(new Runnable() {
	                        		final String status=line;
		                            @Override
		                            public void run() {
		                           updateUI(line);
		                           
										result=line.toString();
										StatusConnect=1;
										
		                            }
		                        });
		                     
	                        	/*(new Thread(new Runnable() {
									
									@Override
									public void run() {
										// TODO Auto-generated method stub
										final String status=line;
										myHandler.post(new Runnable() {
											
											@Override
											public void run() {
												// TODO Auto-generated method stub
												 Log.d("ServerActivity", line);
												updateUI(line);
												result=line.toString();
												StatusConnect=1;
												
											}
										});
									}
								})).start();*/
	                        }
	                    break;
	                    } catch (Exception e) {
	                        handler.post(new Runnable() {
	                            @Override
	                            public void run() {
	                                serverStatus.setText("Xảy Ra Lỗi Hãy Thử Lại");
	                            }
	                        });
	                        Log.d("Co Loi", e.toString());
	                    }
	                }
	            } else {
	                handler.post(new Runnable() {
	                    @Override
	                    public void run() {
	                        serverStatus.setText("Không Thấy Wifi Được Mở");
	                    }
	                });
	            }
	        } catch (Exception e) {
	            handler.post(new Runnable() {
	                @Override
	                public void run() {
	                    serverStatus.setText("Không Thể Lấy Được IP Từ DHCP");
	                }
	            });
	            Log.d("Co Loi", e.toString());
	        }
	        serverStatus.setText(result);
	        
	        
	    }
	}
 
public class ServerThreadBK implements Runnable {
	
	    public  void run() {
	    	
	        try {
	            if (SERVERIP != null) {
	            handler.post(new Runnable() {
	                    @Override
	                    public void run() {
	                 serverStatus.setText("IP Điện Thoại : " + SERVERIP);
	                  }
	               });
	                serverSocket = new ServerSocket(SERVERPORT);
	                while (true) {
	              
	                	serverStatus.setText(SERVERIP);
	                    // listen for incoming clients
	                    Socket client = serverSocket.accept();
	                    handler.post(new Runnable() {
	                        @Override
	                        public void run() {
	                            serverStatus.setText("Đã Kết Nối Thành Công");
	                        }
	                    });
	                   try {
	                        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
	                        String line = null;
	                        while ((line = in.readLine())!= null)
	                        {
	                        	//line = in.readLine();
	                            Log.d("ServerActivity", line);
	                           serverStatus.setText(line);
	                            result=line.toString();
	                          handler.post(new Runnable() {
	                               @Override
	                           public void run() {
	                                    // set something
	                                    
	                                }
	                            });
	                        }
	                    break;
	                    } catch (Exception e) {
	                        handler.post(new Runnable() {
	                            @Override
	                            public void run() {
	                                serverStatus.setText("Xảy Ra Lỗi Hãy Thử Lại");
	                            }
	                        });
	                        Log.d("Co Loi", e.toString());
	                    }
	                }
	            } else {
	                handler.post(new Runnable() {
	                    @Override
	                    public void run() {
	                        serverStatus.setText("Không Thấy Wifi Được Mở");
	                    }
	                });
	            }
	        } catch (Exception e) {
	            handler.post(new Runnable() {
	                @Override
	                public void run() {
	                    serverStatus.setText("Không Thể Lấy Được IP Từ DHCP");
	                }
	            });
	            Log.d("Co Loi", e.toString());
	        }
	        serverStatus.setText(result);
	        
	        	
	        
	    }
	}


    public class BroadCastThread implements Runnable {
		public void run() {
			try {
				
				SVBroadCast.sendBroadCastInfoToAll();
			
			} catch (Exception e) {
				 Log.d("Co Loi", e.toString());
			}
			
		}
	}
    

}


